package com.ifar.audiosdk.base

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.ifar.audiosdk.R
import com.lxj.xpopup.XPopup
import org.simple.eventbus.EventBus
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
import java.lang.reflect.ParameterizedType


abstract class IfarBaseActivity<VM : IfarBaseViewModel> : ComponentActivity(),
    PermissionCallbacks {
    protected lateinit var mViewModel: VM
    protected lateinit var mContext: Context
    private val requestDialogPermission = 0X1112

    private val permsRequestCode = 0x001    //权限请求code
    private val perms = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.RECORD_AUDIO
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //开启屏幕常亮
        BarUtils.setStatusBarLightMode(this, true)  //设置状态栏颜色
        BarUtils.transparentStatusBar(this) //设置透明状态栏
        setContentView(getLayoutResId())
        initVM()
        initView()
        startObserve()
        initData()
    }

    override fun onResume() {
        super.onResume()
        requestSettingCanDrawOverlays()
    }

    private fun requestSettingCanDrawOverlays() {
        if (!Settings.canDrawOverlays(this)) {
            XPopup.Builder(this).asConfirm(
                "悬浮框权限", "请打开悬浮框权限，否则部分功能无法正常使用"
            ) {
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                intent.data = Uri.parse("package:$packageName")
                startActivityForResult(intent, requestDialogPermission)
            }.show()
        } else {
            EasyPermissions.requestPermissions(
                this, getString(R.string.permission_rationale), permsRequestCode, *perms
            )
        }

    }


    abstract fun getLayoutResId(): Int

    private fun initVM() {
        mContext = this
        ARouter.getInstance().inject(this)
        mViewModel = ViewModelProvider(this).get(getClass(this))
        mViewModel.let(lifecycle::addObserver)
    }

    abstract fun initView()
    open fun startObserve() {}
    abstract fun initData()

    fun <T> getClass(t: Any): Class<T> {
        // 通过反射 获取父类泛型 (T) 对应 Class类
        return (t.javaClass.genericSuperclass as ParameterizedType)
            .actualTypeArguments[0] as Class<T>
    }

    protected fun startActivity(z: Class<*>) {
        startActivity(Intent(this, z))
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        mViewModel.let { lifecycle.removeObserver(it) }
        super.onDestroy()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        if (requestCode == permsRequestCode && perms.size == this.perms.size) {
            // TODO: 2021-04-08 同意全部请求
            initGlass()
        }
    }

   open fun initGlass(){}

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this)
                .setTitle(R.string.permission_title)
                .setRationale(R.string.permission_rationale)
                .setNegativeButton(R.string.cancel)
                .setPositiveButton(R.string.sure)
                .build()
                .show()
        }
    }

}